package com.base.cn.platform.os.service.user.exprule;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.action.ActionKey;
import com.base.cn.platform.os.dao.user.exprule.CusUserExpAccountDao;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpAccount;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpRecord;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpRule;
import com.base.cn.platform.os.entity.user.integral.CusUserIntegralRule;
import com.base.cn.platform.os.service.user.gradeconfig.CusUserGradeConfigBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 经验账户Biz
 * Created by ll on 2018/4/20
 */
@Service
public class CusUserExpAccountBiz extends BaseBiz<CusUserExpAccount,CusUserExpAccountDao> {

    @Autowired
    private CusUserExpRuleBiz cusUserExpRuleBiz;
    @Autowired
    private CusUserGradeConfigBiz cusUserGradeConfigBiz;
    @Autowired
    private CusUserExpRecordBiz cusUserExpRecordBiz;


    /**
     * 获取sql语句
     * @param userGrade
     * @return
     */
    public String whereSql(CusUserExpAccount userGrade){
        String whereSql =" 1=1 ";
        if(ObjectUtils.isNotEmpty(userGrade)){
            if(StringUtils.isNotEmpty(userGrade.getUserId())){
                whereSql += " and userId =  " + userGrade.getUserId()   ;
            }
            if(StringUtils.isNotEmpty(userGrade.getExp())){
                whereSql += " and exp =" + userGrade.getExp()  ;
            }
        }
        return whereSql;
    }

    /**
     * 搜索公共列表
     * @param userGrade  查询条件
     * @param count  分页条件
     * @return
     */
    public List<CusUserExpAccount> getUserExpAccountList(CusUserExpAccount userGrade, Integer count, List<String> columns){
        String whereSql =whereSql(userGrade);
        return this.find(whereSql,count,columns);
    }


    /**
     * 用户用
     * @param userIds
     * @return
     */
    public  List<CusUserExpAccount>  queryCusUserExpAccountListByUserIds(String userIds){
        List<CusUserExpAccount> cusUserExpAccounts = new ArrayList<>();
        userIds=StringUtils.subHeadTailString(userIds,",");
        if(StringUtils.isNotEmpty(userIds)){
            cusUserExpAccounts = this.find(" userId in ("+userIds+")",null,new ArrayList<>());
        }
        return cusUserExpAccounts;
    }


    /**
     * 根据用户Id 搜索用户积分
     * @param userId 用户ID
     * @return CusUserExpAccount
     */
    public CusUserExpAccount queryUserGradeByUserId(BigDecimal userId){
        CusUserExpAccount userGrade = new CusUserExpAccount();
        if(DataUtil.idIsNotNull(userId)){
            userGrade.setUserId(userId);
            List<CusUserExpAccount> userGrades = this.getUserExpAccountList(userGrade,null,new ArrayList<>());
            if(ObjectUtils.isNotEmpty(userGrades)){
                userGrade =  userGrades.get(0);
            }else{
                userGrade = new CusUserExpAccount();
                userGrade.setUserId(userId);
                userGrade.setExp(0L);
                this.save(userGrade);
            }
        }
        return userGrade;
    }

    /**
     * 添加用户经验
     * @param ruleList 积分的规则
     * @param userId 用户ID
     * @param otherId 第三方ID
     */
/*    @Async
    @Transactional(rollbackFor = IllegalArgumentException.class)
    public void addUserExp(List<CusUserIntegralRule> ruleList, BigDecimal userId, BigDecimal otherId){
        String keys = ruleList.stream().map(e->e.getActionKey().toString()).collect(Collectors.joining("','","'","'"));
        //获取经验规则
        List<CusUserExpRule> cusUserExpRuleList = cusUserExpRuleBiz.find(" (actionKey in ("+keys+") or actionKey='userLevel6') and status=1",null,null);
        if(ObjectUtils.isNotEmpty(cusUserExpRuleList)){
            Map<String,CusUserExpRule> cusUserExpRuleMap = cusUserExpRuleList.stream().collect(Collectors.toMap(e->e.getActionKey(), e->e));
            int userLevel =1;
            //6级（含6）以上学员获取双倍经验
            CusUserExpRule userLevel6 = cusUserExpRuleMap.get(ActionKey.userLevel6);
            //用户等级对象
            CusUserExpAccount expAccount = queryUserGradeByUserId(userId);
            if(ObjectUtils.isNotEmpty(userLevel6)){
                //用户等级
                userLevel = cusUserGradeConfigBiz.queryUserLevel(expAccount.getExp());
            }
            List<CusUserExpRecord> cusUserExpRecordList = new ArrayList<>();
            int _userLevel = userLevel;
            cusUserExpRuleList.forEach(e->{
                if(!e.getActionKey().equals(ActionKey.userLevel6)){
                    CusUserExpRecord record = new CusUserExpRecord();
                    record.setRuleId(e.getId());
                    record.setUserId(userId);
                    record.setOtherId(otherId);
                    if(_userLevel >=6){
                        record.setExp(e.getScore().intValue()*2);
                    }else{
                        record.setExp(e.getScore().intValue());
                    }
                    record.setDepict(e.getTermDepict());
                    cusUserExpRecordList.add(record);
                }
            });
            if(ObjectUtils.isNotEmpty(cusUserExpRecordList)){
                long sumScore = cusUserExpRuleList.stream().mapToLong(CusUserExpRule::getScore).sum();
                if(_userLevel >=6){
                    sumScore = sumScore * 2;
                }
                //重新设置用户经验
                expAccount.setExp(expAccount.getExp().longValue() + sumScore);
                //更新
                this.updateById(expAccount,null);
                //添加经验记录
                cusUserExpRecordBiz.batchSave(cusUserExpRecordList);
            }
        }
    }*/

}
